﻿using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using viBook.Common;
using viBook.Models;
using viBook.Repositories;

namespace viBook.Controllers
{
    public class BaseController : Controller
    {
        protected readonly JsonResult FailedFeedback;
        protected readonly JsonResult SuccessFeedback;
        private readonly IUserRepository _userRepository;

        protected BaseController()
        {
            SuccessFeedback = Json(new {success = true});
            FailedFeedback = Json(new {success = false, message = Constant.ErrorMessage});
            _userRepository = new UserRepository();
        }

        protected internal ExtendedIdentity ExtendedIdentity
        {
            get { return User.Identity as ExtendedIdentity; }
        }

        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            HttpCookie cookie = HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
            if (cookie != null)
            {
                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
                string name = ticket.Name;
                SessionPersiter.User = _userRepository.FindByEmail(name);
            }
            User user = SessionPersiter.User;
            filterContext.HttpContext.User = new ExtendedPrincipal(new ExtendedIdentity(user));
        }
    }

    public static class SessionPersiter
    {
        private const string UsernameSession = "user";

        public static User User
        {
            get
            {
                if (HttpContext.Current.Session == null)
                {
                    return null;
                }
                object sessionVal = HttpContext.Current.Session[UsernameSession];
                return sessionVal != null ? sessionVal as User : null;
            }
            set { HttpContext.Current.Session[UsernameSession] = value; }
        }
    }
}